const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectId;
const url = `mongodb://localhost:27017`;
const dbs = "fangyi_2021";
const coll_profiles = "profiles";
const fs = require("fs");

const get_format_date = (fmt) => {
  fmt = fmt || "yyyy-MM-dd hh:mm";
  var date = new Date();
  var o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds(), //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};

const PrefixZero = (num, n) => {
  return (Array(n).join(0) + num).slice(-n);
};

const get_numberid = (ids) => {
  var date = new Date();
  var y = date.getFullYear().toString().substr(2);
  var m = PrefixZero(date.getMonth() + 1, 2);
  var id = (Math.round(new Date() / 1000) + Math.round(new Date() / 500) + ids)
    .toString()
    .substr(8);
  return `BL-${y}${m}-${id}`;
};

module.exports = {
  db: null,
  open(coll) {
    return new Promise(function (resolve, reject) {
      MongoClient.connect(url, { useUnifiedTopology: true }, (err, client) => {
        if (err) {
          throw new Error(err);
        }
        this.db = client.db(dbs);
        resolve(this.db.collection(coll));
      });
    });
  },
  close() {
    if (this.db) {
      this.db.close();
    }
  },
  find_all(props) {
    const { query, skip, limit } = props;
    return new Promise((resolve, _reject) => {
      this.open(coll_profiles).then((coll) => {
        let pm = coll.find(query);
        pm.count().then((count) => {
          console.log("查询到数据:", count);
          pm.sort({ _id: -1 })
            .limit(limit)
            .skip(skip)
            .toArray((err, result) => {
              if (err) throw new Error(err);
              var data = result.map((row, id) => ({
                ...row,
                key: id,
                序号: id + 1,
              }));
              this.close();
              resolve({ count: count, data: data });
            });
        });
      });
    });
  },
  find_one(props) {
    const { query, skip, limit } = props;
    return new Promise((resolve, _reject) => {
      query._id = ObjectId(query._id);
      this.open(coll_profiles).then((coll) => {
        coll.findOne(query).then((doc) => {
          console.log("找到数据：1");
          this.close();
          resolve(doc);
        });
      });
    });
  },
  save_profile(data) {
    return new Promise((resolve, _reject) => {
      this.open(coll_profiles).then(async (coll) => {
        for (const row of data) {
          var pr = await coll.findOne({ 身份证号: row["身份证号"] });
          if (pr) {
            let pam = {}
            for (let i in row) {
              if (row[i] !== null) {
                pam[i] = row[i]
              }
            }
            pam["数据来源"] += `;${pr["数据来源"]}`;
            let op = pam['数据来源'].split(';')
            function unique1(arr) {
              var hash = [];
              for (var i = 0; i < arr.length; i++) {
                if (hash.indexOf(arr[i]) == -1) {
                  hash.push(arr[i]);
                }
              }
              return hash;
            }
            pam["数据来源"] = unique1(op).join('； ')
            pam["操作记录"] += `;${pr["操作记录"]}`;
            await coll
              .updateOne({ _id: pr._id }, { $set: { ...pam } })
              .then(console.log(pam['姓名'],"有重复的数据，已更新！"));
          } else {
            row["编号"] = get_numberid(Math.round(new Date()));
            row["录入时间"] = get_format_date();
            await coll.insertOne(row).then(console.log("保存一条数据成功！"));
          }
        }
        this.close();
        resolve(true);
      });
    });
  },
  update_one(data) {
    return new Promise((resolve, _reject) => {
      this.open(coll_profiles).then((coll) => {
        let query = { _id: ObjectId(data._id) };
        delete data._id;
        coll.updateOne(query, { $set: { ...data } }).then(() => {
          console.log("1条数据，已更新！");
          this.close();
          resolve(true);
        });
      });
    });
  },
  delete(query) {
    return new Promise((resolve, reject) => {
      let querys = { _id: { $in: query.map(id => ObjectId(id)) } };
      this.open(coll_profiles).then((coll) => {
        coll.deleteMany(querys).then(() => {
          console.log("删除" + query.length + "条数据成功！");

          this.open("img_files").then((colls) => {
            let imgquerys = { id: { $in: query.map(id => id) } };
            colls.find(imgquerys, { _id: 0, id: 0 }).toArray((err, docs) => {
              let doc = { _id: { $in: docs.map(id => id._id) } }
              colls.deleteMany(doc).then(() => {
                docs.forEach(it => {
                  fs.unlinkSync("./uploads/imgs/" + it.filename);
                });
                console.log("相关图片数据删除成功");
              })
            });
          });


          this.close();
          resolve(true);
        });
      });
    });
  },
  upload_img(data) {
    return new Promise((resolve, reject) => {
      this.open("img_files").then((coll) => {
        coll.insertOne(data).then(() => {
          this.close();
          resolve(true);
        });
      });
    });
  },
  find_img(id) {
    return new Promise((resolve, reject) => {
      this.open("img_files").then((coll) => {
        coll.find({ id: id }, { _id: 0, id: 0 }).toArray((err, docs) => {
          this.close();
          resolve(docs);
        });
      });
    });
  },
  remove_img(data) {
    return new Promise((resolve, reject) => {
      query = { _id: ObjectId(data._id) };
      this.open("img_files").then((coll) => {
        coll.deleteOne(query).then(() => {
          console.log("图片档案删除成功！");
          fs.unlinkSync("./uploads/imgs/" + data.filename);
          this.close();
          resolve(true);
        });
      });
    });
  },
  login(data) {
    return new Promise((resolve, reject) => {
      this.open("user").then((coll) => {
        coll.findOne(data).then((doc) => {
          this.close();
          resolve(doc);
        });
      });
    });
  },
  get_user() {
    return new Promise((resolve, reject) => {
      this.open("user").then((coll) => {
        coll.find({}).toArray((err, docs) => {
          this.close();
          resolve(docs);
        });
      });
    });
  },
  add_user(data) {
    return new Promise((resolve, reject) => {
      this.open("user").then(async (coll) => {
        var user = await coll.findOne({ user: data.user });
        console.log(user);
        if (user) {
          console.log(data.user, "已有相同账号！");
          this.close();
          resolve(false);
        } else {
          coll.insertOne(data).then(() => {
            console.log(data.user, "账号添加！");
            this.close();
            resolve(true);
          });
        }
      });
    });
  },
  update_user(data) {
    return new Promise((resolve, _reject) => {
      this.open("user").then((coll) => {
        let query = { _id: ObjectId(data._id) };
        delete data._id;
        coll.updateOne(query, { $set: { ...data } }).then(() => {
          console.log(data.user, "账号已更新！");
          this.close();
          resolve(true);
        });
      });
    });
  },
  delete_user(query) {
    return new Promise((resolve, reject) => {
      query = { _id: ObjectId(query._id) };
      this.open("user").then((coll) => {
        coll.deleteOne(query).then(() => {
          console.log("账号删除成功！");
          this.close();
          resolve(true);
        });
      });
    });
  },
};
